package Day2025_02_28;

public class LeetCodeLCR159 {
    public int[] inventoryManagement(int[] stock, int cnt) {
        createHeap(stock);
        int end = stock.length - 1;
        while (end > 0) {
            swap(stock, 0, end);
            sitfDown(stock, 0, end);
            end--;
        }
        int[] array = new int[cnt];
        for (int i = 0; i < cnt; i++) array[i] = stock[i];
        return array;
    }
    private void createHeap (int[] nums) {
        int n = nums.length;
        int parent = (n - 1 - 1) / 2;
        for ( ; parent >= 0; parent--) sitfDown(nums, parent, n);
    }
    private void sitfDown (int[] nums, int parent, int len) {
        int child = parent * 2 + 1;
        while (child < len) {
            if (child + 1 < len && nums[child] < nums[child + 1]) child++;
            if (nums[child] > nums[parent]) {
                swap(nums, parent, child);
                parent = child;
                child = parent *2 + 1;
            } else break;
        }
    }
    private void swap (int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
